import React, { Component } from 'react'
import axios from 'axios'
import PubSubJS from 'pubsub-js'

import './index.css'


export default class List extends Component {

    // 使用PubSubJS进行任意组件间的通信
    // 因此不需要将状态信息保存在App组件中
    state = {
        users:[],
        // 0: 表示有用户需要展示
        // 1: 表示第一次展示
        // 2: 表示加载中
        // 3: 表示有异常
        status: 1, // 记录页面展示的状态
        message: 'error' // 保存异常的信息
    }


    updateState = async (msg, keyword) => {
        try {
            // 查看github提供的api接口 https://api.github.com/
            this.setState({status:2})
            const response = await axios.get(`https://api.github.com/search/users?q=${keyword}`)
            const users = response.data.items
            this.setState({status:0, users})
        } catch(error) {
            const {message} = error
            this.setState({status:3, message})
        }
    }

    componentDidMount = () => {
        // 组件挂载成功后，开始订阅消息，并更新状态
        this.token = PubSubJS.subscribe('Search', this.updateState)
    }

    componentWillUnmount = () => {
        PubSubJS.unsubscribe(this.token)
    }
      
    render() {
        const {users, status, message} = this.state
        return (
            <div className="card-body text-center">
            {
                status === 1 ? (
                    '请输入关键字，并开始检索'
                ) : status === 2 ? (
                    'Loading......'
                ) : status === 3 ? (
                    <span className="text-danger">{message}</span>  
                ) :
                    <div className="row">
                         {users.map((userObj) => {
                             const {id, avatar_url, login, html_url} = userObj
                             return (
                                <div key={id} className="col-4 user-item">
                                    <a href={html_url} target="_blank" rel="noreferrer"><img alt="" src={avatar_url} style={{height: '80%'}}></img></a>
                                    <div>{login}</div>
                                </div>
                             )})}
                    </div>
            }
            </div>
        )
    }
}
